<?php namespace Common\Model;
use Hdphp\Model\Model;
/*文章模型*/
class Article extends Model
{
	/*写入表*/
	protected $table = "article";
	/*自动验证*/
	protected $validate = array(
		array('title','required','文章标题不能为空',3,3),
		array('author','required','请输入文章作者',3,3),
		array('category_cid','required','请选择所属分类',3,3),
	);
	
	/*自动完成*/
	//array(表单字段名,处理方法,方法类型,验证条件,处理时间) 
	protected $auto = array(
		array("sendtime","time","function",3,1),
		array("updatetime","time","function",3,2),
		//自定义方法处理
		array("user_uid","Useruid","method",3,1),
		array("thumb","image","method",3,3),
	);
	/*自定义方法，user_uid 登陆者uid*/
	public function Useruid()
	{
		return 	$_SESSION['uid'];
		
	}
	/*自定义方法，thumb 处理缩略图*/

	public function image()
	{
		//设置上传路径
		$path = "Upload/" . date("ymd");
		$file = Upload::type('jpg,png,txt')->path($path)->size(2000000)->make();
		//如果有文件上传的时候
		if($file)
		{
			//缩略
			//Image::thumb($file, $outFile, $thumbWidth, $thumbHeight, $thunbType);
			//参数：上传过来的图片路径|存储路径|缩略宽|缩略高|缩略方式
			//Upload/160516/thumb_95311463370084.JPG
			$thumbPath = Image::thumb($file[0]['path'],$path . "/thumb_" . $file[0]['basename'],200,200,5);
			return $thumbPath;
		}else
		{
			//如果没有文件上传的时候
			return "";
		}		
	}
	
	
	/*添加*/
	public function store()
	{
//		var_dump($_POST);
		
		
		/*实例化ArticleData*/
		$ArticleDataModel = new \Common\Model\ArticleData;
		/*自动验证*/
		if(!$this->create()) return false;
		if(!$ArticleDataModel->create())
		{
			/*获取$ArticleDataModel 错误信息*/
			$this->error=$ArticleDataModel->getError();
			return false;
		}
		//1.执行文章添加
		$aid = $this->add();
//		p($aid);
		//2.执行文章标签的添加
		//实例化Arcticletag
		$arcTagModel = new \Common\Model\ArticleTag;
		foreach (Q("post.tag_tid",array()) as $k => $v) {
			$data = array(
				"article_aid" =>$aid,
				"tag_tid" => $v,
			);
			$arcTagModel->add($data);
		}
		//3.添加文章数据表
		//add添加的时候，添加的是模型中data属性当中的值
		$ArticleDataModel->data['article_aid'] = $aid;
		$ArticleDataModel->add();
		
		return true;
		
	}
	/*编辑*/
	public function edit($aid)
	{
		/*实例化article_data*/
		$articleDataModel = new \Common\Model\ArticleData;
		
		/*自动验证*/
		if(!$this->create()) return false;
		if(!$articleDataModel->create()){
			/*获取$ArticleDataModel 错误信息*/
			$this->error = $articleDataModel->getError();
			return false;
		}
		var_dump($_FILES);
		/*上传的错误信息*/
		if(isset($_FILES['thumb']) && $_FILES['thumb']['error'] !=4 )
		{
			//上传错误信息
			if($error = Upload::getError())
			{
				$this->error = $error;
				return false;
			}
			
		}
		
		/*执行修改*/
		$this->save();
		/*article_tag 文章标签表*/
		$arctagModel = new \Common\Model\ArticleTag;
		//将原来的删掉
		$arctagModel->where("article_aid",$aid)->delete();
		//修改标签
		foreach ($_POST['tag_tid'] as $k => $v) {
				$data = array(
					"article_aid"=>$aid,
					"tag_tid"=>$v,
				);
				$arctagModel->add($data);
		
		}
		//修改文章数据表
		$articleDataModel->where("article_aid",$aid)->save();
		
		
		
		return true;

		
	}
	
	
}


















